package com.example.jay.myapplication;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.*;
import android.database.sqlite.SQLiteDatabase;
import android.os.CountDownTimer;
import android.os.Environment;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.*;
import pub.devrel.easypermissions.EasyPermissions;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class MainActivity extends AppCompatActivity {

   /* @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }*/
    private static final int REQUEST_ENABLE_BT = 2;
    TextView txt;
    TextView txt_see;
    // TextView txt_scan;
    BluetoothAdapter mBluetoothAdapter;
    ArrayAdapter<String> mArrayAdapter;
    Button btn_switch;
    Button btn_see;
    Button btn_scan;
    Button btn_stop;
    ListView list;
    CountDownTimer see_timer;
    // CountDownTimer scan_timer;
    int m=1;
    int index_txt= 0;
    int index_c=0;
    boolean IsCreat;
    //SQLiteDatabase db;
    String path;
    public static String lastPath;
    private static final int RC_STORAGE_PERM = 123;
    private static final String[] NEED_PERMISSIONS =
            {Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.ACCESS_COARSE_LOCATION};

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //initData();
        EasyPermissions.requestPermissions(this, "App需要读写SD卡以及位置的权限", RC_STORAGE_PERM, NEED_PERMISSIONS);

        txt = (TextView)findViewById(R.id.textView1);
        txt_see = (TextView)findViewById(R.id.textView2);
        //txt_scan = (TextView)findViewById(R.id.textView3);
        //绑定XML中的ListView，作为Item的容器
        list = (ListView) findViewById(R.id.listView1);

        //获取蓝牙适配器
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        mArrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1);
        if (mBluetoothAdapter == null) {
            // Device does not support Bluetooth
            txt.setText("fail");
            //退出程序
            MainActivity.this.finish();
        }

        btn_switch = (Button)findViewById(R.id.button1);
        btn_switch.setOnClickListener(new switchButtonListener());
        // btn_scan.setOnClickListener(new ButtonListener());
        btn_see = (Button)findViewById(R.id.button2);
        btn_see.setOnClickListener(new seeButtonListener());
        btn_see.setEnabled(false);
        btn_scan = (Button)findViewById(R.id.button3);
        btn_scan.setOnClickListener(new scanButtonListener());
        btn_scan.setText("扫描");

        btn_stop = (Button)findViewById(R.id.button4);
        btn_stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                handler.removeCallbacks(updateThread);
                mBluetoothAdapter.disable();
                Toast.makeText(MainActivity.this, "蓝牙已关闭", Toast.LENGTH_SHORT).show();
                index_c=0;
                m = 0;
                index_txt++;
                try {
                    FilesHandler.handleTxt(lastPath);
                } catch (IOException e) {
                    e.printStackTrace();
                    Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
        });
        btn_stop.setText("停止扫描");

        // btn_del.findViewById(R.id.button4);
        // btn_del.setOnClickListener(new delButtonListener());
        //btn_del.setEnabled(!flag);

        //判断蓝牙是否已经被打开
        if (mBluetoothAdapter.isEnabled()) {
            //打开
            btn_switch.setText("ON");
            btn_see.setEnabled(true);
            btn_scan.setEnabled(true);
            Toast.makeText(this, "蓝牙已打开", Toast.LENGTH_SHORT).show();
        }

        see_timer = new CountDownTimer(120000,1000) {
            @Override
            public void onTick( long millisUntilFinished)
            {
                txt_see.setText( "剩余可见时间" + millisUntilFinished / 1000 + "秒");
            }
            @Override
            public void onFinish()
            {
                //判断蓝牙是否已经被打开
                if (mBluetoothAdapter.isEnabled())
                {
                    btn_see.setEnabled(true);
                    txt_see.setText( "设备不可见");
                }
            }
        };
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        android.os.Process.killProcess(android.os.Process.myPid());
    }




    class switchButtonListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            String str = btn_switch.getText().toString();
            if (str.equals("OFF")) {
                if (!mBluetoothAdapter.isEnabled()) {
                    //打开蓝牙
                    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                    startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
                    txt.setText("s1");
                    btn_see.setEnabled(true);
                    btn_scan.setText("扫描");
                    btn_scan.setEnabled(true);
                }
            }
            else {
                //关闭蓝牙
                mBluetoothAdapter.disable();
                btn_switch.setText("OFF");
                mArrayAdapter.clear();
                list.setAdapter(mArrayAdapter);
                btn_see.setEnabled(false);
                btn_scan.setEnabled(false);
            }
        }
    }

    class seeButtonListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            //开启可见
            Intent enableBtIntent_See = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
            startActivityForResult(enableBtIntent_See, 3);
            txt.setText("s1");
            btn_see.setEnabled(false);
            see_timer.start();

        }
    }

    Handler handler = new Handler();
    Runnable updateThread = new Runnable(){

        @Override
        public void run() {
            // TODO Auto-generated method stub
            String str = btn_scan.getText().toString();
            ++index_c;
            if (mBluetoothAdapter.isEnabled()) {
                //开始扫描
                mBluetoothAdapter.startDiscovery();
                txt.setText("正在扫描周围蓝牙设备！");
                if(!IsCreat) {
                    // Create a BroadcastReceiver for ACTION_FOUND
                    //final myReceiver mReceiver = new myReceiver (this)
                    final BroadcastReceiver mReceiver = new BroadcastReceiver()
                    {
                        @Override
                        public void onReceive(Context context, Intent intent)
                        {
                            // TODO Auto-generated method stub
                            String action = intent.getAction();
                            // When discovery finds a device
                            //mArrayAdapter.clear();
                            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                                // Get the BluetoothDevice object from the Intent
                                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                                // Add the name and address to an array adapter to show in a ListView
                                String name=device.getName();
                                short rssi = intent.getExtras().getShort(

                                        BluetoothDevice.EXTRA_RSSI);
                                String rssiStr = String.valueOf(rssi);

                                //Toast.makeText(this.getContext(), "" +name   + rssiStr, Toast.LENGTH_SHORT).show();

                                if (name != null && name.length() > 12) {
                                    if (name.substring(0, 10).equals("MiniBeacon")) {
                                        mArrayAdapter.add(m+"--"+index_c+"："+ name + ":" + rssiStr +" mac:"+device.getAddress());
                                        appendtxt(device.getName()+",mac:"+device.getAddress()+",rssi:"+rssiStr);
                                        Log.i("tag","扫描了："+m);
                                        Log.i("tag","扫描了："+rssiStr +name);
                                        txt.setText(String.valueOf(m));
                                        m++;
                                    }
                                }
                                if(list!=null)
                                    list.removeAllViewsInLayout();
                            }
                            list.setAdapter(mArrayAdapter);
                        }

                    };
                    // Register the BroadcastReceiver
                    IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
                    registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy
                    IsCreat=true;
                }
            }
            handler.postDelayed(updateThread, 2000);
        }
    };

    class scanButtonListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            if (mArrayAdapter != null) {
                mArrayAdapter.clear();
            }
            initsavetxt();
            handler.post(updateThread);
        }
    }

    String time;
    private  void initsavetxt() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");// HH:mm:ss
        //获取当前时间
        Date date = new Date(System.currentTimeMillis());
        //time1.setText("Date获取当前日期时间"+simpleDateFormat.format(date));
        time=simpleDateFormat.format(date)+"";
        File sdCardDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS), "蓝牙");//Environment.DIRECTORY_DOWNLOADS
        if (!sdCardDir.exists()) {
            if (!sdCardDir.mkdirs()) {

                try {
                    sdCardDir.createNewFile();

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        try {
            //新建文件
            Toast.makeText(this,sdCardDir.getAbsolutePath(),Toast.LENGTH_SHORT).show();
            String tt=time+"log.txt";
            File saveFile = new File(sdCardDir, tt);
            path = sdCardDir.getAbsolutePath();
            if (!saveFile.exists()) {
                saveFile.createNewFile();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    void appendtxt(String content) {
        lastPath = path+"/"+time+"log.txt";//com.example.jay.myapplication
        FileWriter writer = null;
        try {
            // 打开一个写文件器，构造函数中的第二个参数true表示以追加形式写文件
            writer = new FileWriter(lastPath, true);
            writer.write(content + "\r\n");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(writer != null){
                    writer.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
